import BaseComponent from "../../../pages/BaseComponent";
import {View} from "@tarojs/components";
import {observable} from "mobx";
import "./index.less";
import LogService from "../../../service/LogService";
import Taro from "@tarojs/taro";
import {observer} from "mobx-react";

@observer
export default class extends BaseComponent {

  @observable progressValue = 50;

  progressLeft = 1;
  progressRight = 1;
  progressWidth = 1;

  getTag() {
    return "Lprogress";
  }

  componentDidMount() {
    super.componentDidMount();
    const {progress} = this.props;
    if (!progress)
      this.progressValue = 50;
    else
      this.progressValue = progress;
  }

  onTouchStart = (e) => {
    LogService.debug('onTouchStart', this, e)
    this.scrollFlag = true;

    // onReady 触发后才能获取小程序渲染层的节点
    if (this.progressLeft > 1)
      this.changeProgress(e);
    else {
      Taro.createSelectorQuery().select('#l_progress_index_only')
        .boundingClientRect()
        .exec(res => {
          LogService.debug("l_progress_index_only", res)
          const {left, right, width} = res[0];
          this.progressLeft = left;
          this.progressRight = right;
          this.progressWidth = width;

          this.changeProgress(e);
        });
    }

  }

  onTouchEnd = (e) => {
    LogService.debug('onTouchEnd', e)
    this.scrollFlag = false;

    const {onProgress} = this.props;
    if (!!onProgress)
      onProgress(this.progressValue);
  }

  onTouchMove = (e) => {
    this.changeProgress(e);
  }

  changeProgress = (e) => {
    const pageX = e.changedTouches[0].pageX;
    let progress = (pageX - this.progressLeft) * 100 / this.progressWidth;
    // LogService.debug('onTouchMove', progress, e);

    if (progress < 10 || progress > 100)
      return;
    let value = parseInt(progress);
    if (value > 95)
      this.progressValue = 100;
    else
      this.progressValue = Math.round(value / 10) * 10;
  }

  render() {

    // LogService.debug("render", this.progressValue);

    const {disabled} = this.props;

    let touchProps = {
      onTouchStart: this.onTouchStart,
      onTouchMove: this.onTouchMove,
      onTouchEnd: this.onTouchEnd,
    }
    if (disabled)
      touchProps = {};

    let value = this.progressValue - 8;
    if (this.progressValue > 15)
      value = this.progressValue - 10;
    if (value < 0)
      value = 0;

    return (
      <View className='l_progress_index' id='l_progress_index_only'

      >
        <View className='l_progress_bg'
              {...touchProps}
        />
        <View className='l_progress' style={{width: (this.progressValue - 2) + '%'}}
              {...touchProps}
        />
        <View className='progress_text'
              style={{left: value + '%'}}
              {...touchProps}
        >
          {this.progressValue}
        </View>
      </View>
    );
  }
}
